<template>
  <view class="user">
    <u-sticky offset-top="0" h5-nav-height="0" bg-color="transparent">
      <u-navbar
        :is-back="false"
        :title-bold="true"
        :is-fixed="false"
        :border-bottom="false"
        :background="{ background: '#FFFFFF' }"
        :title-color="'#333333'"
      ></u-navbar>
    </u-sticky>
    <view class="flex-1" style="min-height: 0">
      <view class="user-info">
        <!-- Header -->
        <view class="header">
          <view class="info flex col-top">
            <view class="flex flex-1">
              <image
                class="logo m-r-20 flex-none"
                :src="
                  isLogin ? user_info.avatar : '/static/images/icon_portrait'
                "
              />
              <template v-if="isLogin">
                <view class="name">
                  <view class="lg black bold line-2">{{ user_info.name }}</view>
                  <view class="account">
                    <view class="text-primary">当前身份：{{ roleName }}</view>
                  </view>
                </view>
              </template>
              <template v-if="!isLogin">
                <view class="xl">点击登录</view>
              </template>
            </view>
            <view class="location-info">
              <image
                style="width: 18.82rpx; height: 23rpx; margin-right: 16rpx"
                src="/static/images/dingwei.png"
              />
              <span v-if="address" class="dwname">{{ topAddress }}</span>
            </view>
          </view>
        </view>

        <!-- Section  -->
        <view class="section">
          <view class="nav bg-white m-t-20">
            <view class="title md bold normal">功能服务</view>

            <view class="nav-item flex flex-wrap">
              <button
                v-for="(item, index) in menuList"
                :key="index"
                :open-type="item.link_type == 2 ? 'contact' : ''"
                class="item flex-col col-center m-b-20"
                style="width: 25%"
                @tap="menuJump(item)"
                hover-class="none"
              >
                <view class="icon-wrapper">
                  <image class="nav-icon" :src="item.image"></image>
                </view>
                <view class="sm nav-name">{{ item.name }}</view>
              </button>
            </view>
          </view>

          <!-- Logout -->
          <view
            class="logout-btn nd bold lighter bg-white flex row-center"
            @click="logout"
            >退出登录</view
          >

          <!-- Edition -->
          <view class="m-20 muted xs flex row-center">版本号v3.12</view>
        </view>
      </view>

      <u-toast ref="uToast" />
    </view>
  </view>
</template>

<script>
import { mapGetters, mapActions } from "vuex";
import { apiLogout, apiMenu } from "@/api/user";
import { apiSetShopInfo } from "@/api/store";
import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins";
import { getLocation } from "@/utils/location";

export default {
  mixins: [MescrollMixin],
  data() {
    return {
      info: {},
      latitude: null,
      longitude: null,
      address: "", // 新增用于存储地址信息
      menuList: [
        {
          name: "发起拼班",
          link: "/pages/initiate_class_share/index",
          image: "/static/images/pb.png",
        },
        {
          name: "发起活动",
          link: "/bundle/launchevent/launchevent",
          image: "/static/images/hd.png",
        },
        {
          name: "排课管理",
          link: "/pages/class_manage/index",
          image: "/static/images/kcjl.png",
        },
        {
          name: "活动管理",
          link: "/pages/activity/release",
          image: "/static/images/hd.png",
        },
        {
          name: "关联小区",
          link: "/pages/link_community/link_community",
          image: "/static/images/hd.png",
        },
        {
          name: "邀请陪伴师",
          link: "/pages/inivite_teacher/index",
          image: "/static/images/hd.png",
        },
      ],
    };
  },
  computed: {
    isLogin() {
      return this.user_info && this.user_info.name;
    },
    topAddress() {
      return this.address || "无法获取地址";
    },
    roleName() {
      return this.user_info?.business?.businessRole?.name || "";
    },
    user_info() {
      return this.$store.state.app.user_info;
    },
  },
  methods: {
    ...mapActions(["getUser"]),
    menuJump(item) {
      this.$Router.push({
        path: item.link,
      });
    },
    getApiMenu() {
      const ossBaseUrl = "https://txjmk-test.oss-cn-shenzhen.aliyuncs.com/"; // OSS基础路径
      apiMenu().then((res) => {
        console.log(res);
        const processMenu = (menus) => {
          if (!Array.isArray(menus)) return [];
          return menus.reduce((acc, menu) => {
            // 先处理当前节点
            if (menu.component) {
              acc.push({
                name: menu.name,
                link: menu.component,
                 image: `${ossBaseUrl}${menu.icon}`
              });
            }
            // 后处理子节点
            if (menu.children) {
              return acc.concat(processMenu(menu.children));
            }
            return acc;
          }, []);
        };
        this.menuList = processMenu(res|| []);
      });
    },
    logout() {
      apiLogout().then((res) => {
        this.$store.commit("logout");
        this.$toast({ title: "退出成功" });
        setTimeout(() => {
          uni.reLaunch({ url: "/pages/login/login" });
        }, 500);
      });
    },
    fetchLocation() {
      getLocation()
        .then((location) => {
          this.latitude = location.latitude;
          this.longitude = location.longitude;
          console.log("获取到的经纬度:", location);
          this.reverseGeocode(location.latitude, location.longitude);
        })
        .catch((error) => {
          console.error("获取地理位置失败:", error);
        });
    },
    // 逆地理编码
    reverseGeocode(latitude, longitude) {
      const url = `https://api.newayz.com/location/hub/v1/track_points?access_key=Cq5k13fcUNmZCyzpI7szHrVdF5pwH9O6`;
      const data = {
        asset: {},
        location: {
          position: {
            point: {
              longitude: longitude,
              latitude: latitude,
            },
          },
        },
      };

      uni.request({
        url: url,
        method: "POST",
        data: data,
        success: (res) => {
          if (
            res.data &&
            res.data.location &&
            res.data.location.address &&
            res.data.location.address.context
          ) {
            const context = res.data.location.address.context;
            const cityInfo = context.find((item) => item.type === "City");
            if (cityInfo) {
              this.address = cityInfo.name;
              console.log("获取到的市:", this.address);
            } else {
              console.error("无法获取市信息");
            }
          } else {
            console.error("无法获取地址信息");
          }
        },
        fail: (error) => {
          console.error("逆地理编码失败", error);
        },
      });
    },
  },
  onShow() {},
  onLoad() {
    this.getApiMenu();

    this.fetchLocation();
  },
};
</script>

<style lang="scss">
page {
  height: 100%;
  padding: 0;
  background: #f8f8f8;
}

.user {
  height: 100%;
  display: flex;
  flex-direction: column;

  &-info {
    position: relative;

    .header {
      padding: 40rpx 20rpx 80rpx 20rpx;
      background: linear-gradient(180deg, #ffffff 0%, #f8f8f8 100%);
      border-radius: 0 0 30rpx 30rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

      .logo {
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        overflow: hidden;
        object-fit: contain;
        box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
      }

      .name {
        text-align: left;
        margin-bottom: 5rpx;
      }

      .account {
        font-size: small;
        margin-top: 10rpx;
      }

      .location-info {
        margin-top: 45rpx;
        display: flex;
        align-items: center;
        color: #666;
      }
    }

    .section {
      padding: 0 20rpx;
      width: 100%;
      margin-top: -40rpx;

      .nav {
        border-radius: 16rpx;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

        .title {
          padding: 24rpx 30rpx;
          margin: 0;
          border-bottom: 1px solid #f0f0f0;
          color: #333;
        }

        &-item {
          padding: 26rpx 0 0;

          .item {
            width: 25%;
            border-radius: 0;
            transition: all 0.3s;

            &:active {
              transform: scale(0.95);
            }
          }

          .icon-wrapper {
            width: 88rpx;
            height: 88rpx;
            border-radius: 16rpx;
            background: #f8f8f8;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 12rpx;
            transition: all 0.3s;
          }

          .nav-icon {
            width: 48rpx;
            height: 48rpx;
            object-fit: contain;
          }

          .nav-name {
            width: 80%;
            height: 40rpx;
            margin: 0 24rpx;
            margin-bottom: 24rpx;
            text-align: center;
            font-size: 28rpx;
            color: #666;
          }
        }
      }

      .logout-btn {
        height: 88rpx;
        border-radius: 16rpx;
        margin: 40rpx 0;
        color: #ff4d4f;
        border: 1px solid #ffccc7;
        transition: all 0.3s;

        &:active {
          background: #fff1f0;
        }
      }
    }
  }
}

.text-primary {
  color: #4caf50;
}
</style>
